package com.ddwl.order.dao.model;

import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.OrderEnum;
import com.ddwl.common.dao.TkDao;
import com.ddwl.common.exception.GlobalException;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.order.dao.OrderSpuDao;
import com.ddwl.order.dao.UpdateAfterSaleOrderBo;
import com.ddwl.order.dao.mapper.AfterSaleOrderMapper;
import com.ddwl.schema.bo.order.ConfirmAfterSaleBo;
import com.ddwl.schema.bo.order.QueryAfterSaleOrderListApiBo;
import com.ddwl.schema.bo.order.QueryAfterSaleOrderListBo;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.order.OrderSpuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
 * (AfterSaleOrder)表数据库访问层
 *
 * @author wenbin
 */
@Slf4j
@Repository
public class ShopAfterSaleOrderDao extends TkDao<AfterSaleOrderMapper, AfterSaleOrder> {

    @Resource
    private OrderSpuDao orderSpuDao;

    public List<AfterSaleOrder> queryAfterSaleOrderApiList(QueryAfterSaleOrderListApiBo bo){
        return baseMapper.queryAfterSaleOrderApiList(bo);
    }

    /**
     * 查询售后订信息
     * @return
     */
    public List<AfterSaleOrder> queryAfterSaleOrderList(QueryAfterSaleOrderListBo bo){
        Example example = getExample();
        example.and().andEqualTo("afterSaleStatus",bo.getAfterSaleStatus())
                .andIn("afterSaleStatus",bo.getAfterSaleBatch())
                .andIn("shopId",bo.getShopIds())
                .andEqualTo("userId",bo.getUserId())
                .andEqualTo("id",bo.getAfterId())
                .andEqualTo("shopId",bo.getShopId())
                .andEqualTo("orderId",bo.getOrderId())
                .andEqualTo("spuOrderId",bo.getSpuOrderId())
                .andEqualTo("platformTag",bo.getPlatformTag())
                .andEqualTo("afterSaleType",bo.getAfterSaleType())
                .andGreaterThanOrEqualTo("gmtCreated",bo.getStartTime())
                .andLessThan("gmtCreated",bo.getEndTime());
        List<AfterSaleOrder> afterSaleOrders = baseMapper.selectByExample(example);
        for (AfterSaleOrder order : afterSaleOrders){
            OrderSpuVo orderSpuVo = BeanConverUtils.convertBean(orderSpuDao.selectByPrimaryKey(order.getSpuOrderId()),OrderSpuVo.class);
            order.setSpu(orderSpuVo);
        }
        return afterSaleOrders;
    }
    /**
     * 查询售后订单数量
     * @return
     */
    public Integer queryAfterSaleOrderCount(QueryAfterSaleOrderListBo bo){
        Integer afterSaleOrdersCount = baseMapper.queryAfterSaleOrderCount(bo);
        return afterSaleOrdersCount;
    }

    /**
     * 查询提交申请订单
     * @return
     */
    public AfterSaleOrder queryAfterSaleOrder(ConfirmAfterSaleBo bo,List<Integer> statuss){
        Example example = getExample();
        example.and()
                .andIn("afterSaleStatus",statuss)
                .andEqualTo("userId",bo.getUserId())
                .andEqualTo("spuOrderId",bo.getSpuOrderId())
                .andEqualTo("orderId",bo.getOrderId());
        List<AfterSaleOrder> afterSaleOrders = baseMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(afterSaleOrders)){
            return afterSaleOrders.get(0);
        }
        return null;
    }


    /**
     * 取消售后单
     * @param afterId
     * @param userId
     */
    public void closed(String afterId,String userId){
        AfterSaleOrder afterSaleOrder =  new AfterSaleOrder();
        afterSaleOrder.setAfterSaleStatus(OrderEnum.AfterStatus.CANCEL.getCode());
        afterSaleOrder.setGmtModified(Instant.now());
        Example example = new Example(AfterSaleOrder.class);
        example.and().andEqualTo("id",afterId)
                .andEqualTo("userId",userId);
        Integer i =baseMapper.updateByExampleSelective(afterSaleOrder,example);
        if(i<1){
            log.error("取消售后单失败 afterOrderNo={}", JSON.toJSONString(afterId));
            throw new GlobalException("取消售后单失败");
        }
    }

    /**
     * 查询订单商品售后中或者售后完成的订单
     * @param orderSpuId
     */
    public List<AfterSaleOrder> queryOrderSpuAfterSale(String orderSpuId){
        AfterSaleOrder saleOrder = new AfterSaleOrder();
        saleOrder.setSpuOrderId(orderSpuId);
        List<AfterSaleOrder> afterSaleOrders = select(saleOrder);
        if(CollectionUtils.isEmpty(afterSaleOrders)){
            return null;
        }
        List<AfterSaleOrder> afterSaleOrders1 = new ArrayList<>();
        afterSaleOrders.forEach(afterSaleOrder -> {
            //过滤掉用户自己取消和我们拒绝的售后单
            if(!OrderEnum.AfterStatus.CANCEL.equals( afterSaleOrder.getAfterSaleStatus())&&
                    !OrderEnum.AfterStatus.REJECT.equals( afterSaleOrder.getAfterSaleStatus())
            ){
                afterSaleOrders1.add(afterSaleOrder);
            }
        });
        return afterSaleOrders1;
    }

    /**
     * 拒绝售后单
     * @param afterId
     * @param reason
     */
    public void reject(String afterId,String reason){
        AfterSaleOrder afterSaleOrder =  new AfterSaleOrder();
        afterSaleOrder.setAfterSaleStatus(OrderEnum.AfterStatus.REJECT.getCode());
        afterSaleOrder.setRejectReason(reason);
        afterSaleOrder.setGmtModified(Instant.now());
        Example example = new Example(AfterSaleOrder.class);
        example.and().andEqualTo("id",afterId);
        Integer i =baseMapper.updateByExampleSelective(afterSaleOrder,example);
        if(i<1){
            log.error("拒绝售后单失败 afterOrderNo={}", JSON.toJSONString(afterId));
            throw new GlobalException("拒绝售后单失败");
        }
    }

    /**
     * 用户更新售后单物流信息
     * @param bo
     */
    public void updateAfter(UpdateAfterSaleOrderBo bo){
        AfterSaleOrder afterSaleOrder =  new AfterSaleOrder();
        //afterSaleOrder.setAfterSaleStatus(OrderEnum.AfterStatus.SEND.getCode());
        afterSaleOrder.setLogisticsName(bo.getLogisticsName());
        afterSaleOrder.setLogisticsCode(bo.getLogisticsCode());
        afterSaleOrder.setLogisticsNo(bo.getLogisticsNo());
        afterSaleOrder.setGmtModified(Instant.now());
        Example example = new Example(AfterSaleOrder.class);
        example.and().andEqualTo("id",bo.getAfterId());
        Integer i =baseMapper.updateByExampleSelective(afterSaleOrder,example);
        if(i<1){
            log.error("添加物流信息失败 afterOrderNo={}", JSON.toJSONString(bo.getAfterId()));
            throw new GlobalException("添加物流信息失败");
        }
    }

    /**
     * 后台填写售后地址
     * @param bo
     */
    public void confirmAfter(ConfirmAfterSaleBo bo, Integer status, Integer afterSaleExpiredTime){
        AfterSaleOrder afterSaleOrder =  new AfterSaleOrder();
        //客服受理
        if (status.equals(OrderEnum.AfterStatus.APPLY.getCode())){
            afterSaleOrder.setAfterSaleStatus(OrderEnum.AfterStatus.ACCEPT.getCode());
            afterSaleOrder.setAfterSaleType(bo.getAfterSaleType());
            afterSaleOrder.setAfterSaleAddr(bo.getAfterSaleAddr());
            afterSaleOrder.setAfterSaleReceiver(bo.getAfterSaleReceiver());
            afterSaleOrder.setAfterSaleTel(bo.getAfterSaleTel());
            afterSaleOrder.setExpiredTime(DateUtil.addDay(Instant.now(),afterSaleExpiredTime));
            //换货
        }else if (status.equals(OrderEnum.AfterStatus.RECEIVED.getCode())){
            afterSaleOrder.setAfterSaleStatus(OrderEnum.AfterStatus.EXCHANGED.getCode());
            afterSaleOrder.setReLogisticsNo(bo.getReLogisticsNo());
            afterSaleOrder.setReLogisticsName(bo.getReLogisticsName());
            afterSaleOrder.setReLogisticsCode(bo.getReLogisticsCode());
            //拒绝退回
        }else if (status.equals(OrderEnum.AfterStatus.REJECT.getCode())){
            afterSaleOrder.setReLogisticsNo(bo.getReLogisticsNo());
            afterSaleOrder.setReLogisticsName(bo.getReLogisticsName());
            afterSaleOrder.setReLogisticsCode(bo.getReLogisticsCode());
        }
        afterSaleOrder.setGmtModified(Instant.now());
        Example example = new Example(AfterSaleOrder.class);
        example.and().andEqualTo("id",bo.getAfterId());
        Integer i =baseMapper.updateByExampleSelective(afterSaleOrder,example);
        if(i<1){
            log.error("添加物流信息失败 afterOrderNo={}", JSON.toJSONString(bo.getAfterId()));
            throw new GlobalException("添加物流信息失败");
        }
    }

    /**
     * 更新订单备注
     * @param bo
     */
    public void updateRemark(ConfirmAfterSaleBo bo){
        AfterSaleOrder afterSaleOrder =  new AfterSaleOrder();
        afterSaleOrder.setGmtModified(Instant.now());
        afterSaleOrder.setRemark(bo.getRemark());
        Example example = new Example(OrderInfo.class);
        example.and().andEqualTo("id",bo.getAfterId());
        Integer i =baseMapper.updateByExampleSelective(afterSaleOrder,example);
        if(i<1){
            log.error("更新订单备注失败 afterOrderNo={}", JSON.toJSONString(bo.getAfterId()));
            throw new GlobalException("更新订单备注失败");
        }
    }


    /**
     * 查询过期售后订单
     * @return
     */
    public List<AfterSaleOrder> selectExpirationOrder(){
        Example example = getExample();
        example.and()
                .andLessThan("expiredTime",Instant.now())
                .andEqualTo("afterSaleStatus", OrderEnum.AfterStatus.ACCEPT.getCode());
        return baseMapper.selectByExample(example);
    }

    /**
     * 查询自动退款订单
     * @return
     */
    public List<AfterSaleOrder> selectAutoRefundOrder(List<Integer> list,List<Integer> types){
        Example example = getExample();
        example.and()
                .andLessThan("autoRefundTime",Instant.now())
                .andIn("afterSaleType",types)
                .andIn("afterSaleStatus",list);
        return baseMapper.selectByExample(example);
    }

    /**
     * 关闭超时的售后订单
     */
    public void afterSaleOrderExpirationClosed(){
        AfterSaleOrder afterSaleOrder =  new AfterSaleOrder();
        afterSaleOrder.setAfterSaleStatus(OrderEnum.AfterStatus.END.getCode());
        afterSaleOrder.setGmtModified(Instant.now());
        Example example = new Example(AfterSaleOrder.class);
        example.and()
                .andLessThan("expiredTime",Instant.now())
                .andEqualTo("afterSaleStatus", OrderEnum.AfterStatus.ACCEPT.getCode());
        baseMapper.updateByExampleSelective(afterSaleOrder,example);
    }

    /**
     * 关闭超时的售后订单
     * @param afterId
     */
    public void afterSaleOrderClosed(String afterId){
        AfterSaleOrder afterSaleOrder =  new AfterSaleOrder();
        afterSaleOrder.setAfterSaleStatus(OrderEnum.AfterStatus.END.getCode());
        afterSaleOrder.setGmtModified(Instant.now());
        Example example = new Example(AfterSaleOrder.class);
        example.and().andEqualTo("id",afterId)
                .andEqualTo("afterSaleStatus", OrderEnum.AfterStatus.ACCEPT.getCode());
        Integer i =baseMapper.updateByExampleSelective(afterSaleOrder,example);
        if(i<1){
            log.error("关闭售后订单失败 afterNo={}", JSON.toJSONString(afterId));
            throw new GlobalException("关闭售后订单失败");
        }
    }


}